﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class MasterPage : System.Web.UI.MasterPage
{
    public List<CustomControlsNS.CustomButton> PageToolbarButtons = new List<CustomControlsNS.CustomButton>();
    public string strPacient = "";
    public string strCfg = "";


    protected override void OnInit(EventArgs e)
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Expires = -1;

        base.OnInit(e);
    }

    public void SetMessage(string strMessage, bool bError)
    {
        if (bError)
            strMessage = "<PRE>" + Server.HtmlEncode(Tools.GetErrorMessage(strMessage)) + "</PRE>";
        strMessage = strMessage.ReplaceNewLineWithBR().Replace("'", "`");
        ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "SetMessage", "DisplayMessage(\"" + strMessage + "\", '" + (bError ? "clsError" : "clsMessage") + "');", true);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //ClientScriptManager cs = Page.ClientScript;
        //cs.RegisterClientScriptResource(this.GetType(),Server.MapPath("~/Scripts/AJAX/ExtenderBase/BaseScripts.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/ExtenderBase/BaseScripts.debug.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/ConfirmButton/confirmButtonBehavior.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/ConfirmButton/confirmButtonBehavior.debug.js"));

        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Common/BaseScripts.debug.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Common/BaseScripts.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Common/Common.debug.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Common/Common.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Common/DateTime.debug.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Common/DateTime.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Common/Input.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Common/Threading.debug.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Common/Threading.js"));
        
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Compat/DragDropScripts.debug.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Compat/DragDropScripts.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Compat/Timer.debug.js"));
        //cs.RegisterClientScriptResource(this.GetType(), Server.MapPath("~/Scripts/AJAX/Compat/Timer.js"));

		bool isAuthenticated = this.Page.User.Identity.IsAuthenticated;
        tdToolbarButtons.Visible = isAuthenticated;
        pnLeftBar.Visible = isAuthenticated;
        pnLeftMenu.Visible = isAuthenticated;

		if (isAuthenticated)
		{
			string userName = this.Page.User.Identity.Name;
			LinkButton lb = (LinkButton)LoginView1.FindControl("lbUserName");
			if (lb != null) lb.Text = userName;
			btnLogOut.Visible = true;
			if (!HasExtraLoginInfo) ReadExtraLoginInfo(userName);
		}
		else
			HasExtraLoginInfo = false;

        if (SiteMap.CurrentNode != null)
        {
            lblPageTitle.Text = SiteMap.CurrentNode.Title;
            this.Page.Title = lblPageTitle.Text;
        }
        else
        {
            if (this.Page.Request.Url.ToString().Contains("Login.aspx"))
            {
                lblPageTitle.Text = Resources.DatabaseStrings.login_LoginButtonText;
                this.Page.Title = Resources.DatabaseStrings.login_LoginButtonText;
            }
        }

        //if (!string.IsNullOrEmpty(Tools.userHipoSession))
        //    btnLogOut.Visible = false;

        for (int i = 0; i < PageToolbarButtons.Count; ++i)
            PlaceHolderToolbarButtons.Controls.Add(PageToolbarButtons[i]);

        lblPacient.Text = strPacient;

        //CustomControlsNS.CustomButton cc = new CustomControlsNS.CustomButton(Resources.DatabaseStrings.logout_LogoutButtonText, Resources.DatabaseStrings.logout_LogoutButtonText, "$get('" + btnLogOut.ClientID + "').click();", "0");
        //PlaceHolderToolbarButtons.Controls.Add(cc);
    }

	private bool HasExtraLoginInfo
	{
		get { return System.Convert.ToBoolean(Session["HasExtraLoginInfo"] ?? false); }
		set
		{
			Session["HasExtraLoginInfo"] = value;
			if (!value)
			{
				Session["StaffId"] = null;
				Session["StaffFirstName"] = null;
			}
		}
	}
	private void ReadExtraLoginInfo(string userName)
	{
		bool status = false;
		
		string sql = @"select u.Name, u.Login, u.StaffID, s.FirstName
			from users u LEFT JOIN staff s ON u.StaffID = s.ID
			where u.Name = '" + userName.Replace("'", "''") + "'";
		//string cookieName = FormsAuthentication.FormsCookieName + "_UserID";
		//if (this.Response.Cookies.AllKeys.Contains<string>(cookieName))
		//    sql += " where u.Name = '" + this.Response.Cookies[cookieName].Value.Replace("'", "''") + "'";
		try
		{
			System.Data.DataTable data = Hipocrate.DB.DBConnection.GetData(sql).Tables[0];
			if (data.Rows.Count == 0) return;
			Session["StaffId"] = data.Rows[0]["StaffId"];
			Session["StaffFirstName"] = data.Rows[0]["FirstName"];
			status = true;
		}
		catch (System.Data.SqlClient.SqlException) { } //TODO: log details, including the query in the sql string.
		catch (ApplicationException) { } //TODO: log details, including the query in the sql string.
		finally
		{
			HasExtraLoginInfo = status; //NB: also deletes existing information if status == false!
		}
	}

    protected void Logout_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Session["UserID"] = null;
        Response.Redirect(this.Page.Request.Url.ToString());
    }

    public CustomControlsNS.CustomButton GetButton(string buttonID)
    {
        foreach (CustomControlsNS.CustomButton b in PageToolbarButtons)
            if (b.ID == buttonID)
                return b;
        return null;
    }

    public string GetUserID()
    {
        if (Session["UserID"] == null)
        {
            Session["UserID"] = Tools.GetUserID(GetUserName(), "");
        }
        if (Session["UserID"] != null)
        {
            return Session["UserID"].ToString();
        }
        else
        {
            FormsAuthentication.SignOut();
            Response.Redirect(this.Page.Request.Url.ToString());
            return null;
        }
    }

    public string GetUserName()
    {
        return System.Threading.Thread.CurrentPrincipal.Identity.Name;
    }
}
